<?php

/**
 * @author hungnq@younetco.com
 */
class Core_Model_DbTable_Entries extends YouNet_Db_Table implements Core_Model_IEntry
{
    const ENTRIES_LATEST        = 0;
    const ENTRIES_MOST_POPULAR  = 1;
    const ENTRIES_RANDOM        = 2;
    
	const TABLE_NAME = 'contest_entries';
	protected $_name = self::TABLE_NAME;
	protected $_rowClass = 'Core_Model_Entry';
	protected $_dependentTables = array(
		'Core_Model_DbTable_EntryInfo'
	);
	private static $_instance;

	/**
	 * @author hungnq
	 * @return Core_Model_DbTable_Entries
	 */
	public static function getInstance()
	{
		if (is_null(self::$_instance))
		{
			self::$_instance = new self();
		}
		return self::$_instance;
	}

	/**
	 * List entries by given id_contest
	 * @param type $id_contest
	 * @return Zend_Paginator
	 */
	public function listByIdContest($id_contest)
	{
		$query = $this->_listByIdContest($id_contest);
		$paginator = Zend_Paginator::factory($query);
		return $paginator;
	}

	/**
	 *
	 * @param type $id_contest
	 * @return type
	 */
	public function _listByIdContest($id_contest)
	{
		$query = $this->select()
				->setIntegrityCheck(false)
				->from($this, array('id', 'image', 'title', 'description', 'votes', 'views', 'id_contest', 'status', 'time_uploaded', 'id_user'))
				->joinLeft(array('u' => 'users'), 'u.id = id_user', array('u.link'))
				->where('id_contest=?', $id_contest)
				->where('status=?', Core_Model_IEntry::STATUS_APPROVED)
				->order('id desc');

		return $this->fetchAll($query);
	}

	/**
	 *
	 * @param type $id_contest
	 * @return type
	 */
	public function _allByIdContest($id_contest)
	{
		$entryFieldTbl = new Core_Model_DbTable_EntryFields();
        
        $registrantFullnameField = $entryFieldTbl->getFieldByIdContest($id_contest, Core_Model_IEntryFields::INDEX_FULL_NAME);
        $id_fullname_field = $registrantFullnameField->id;
        
        $registrantEmailField = $entryFieldTbl->getFieldByIdContest($id_contest, Core_Model_IEntryFields::INDEX_EMAIL);
        $id_email_field = $registrantEmailField->id;
        
		$query = $this->select()
				->setIntegrityCheck(false)
				->from(array('e' => self::TABLE_NAME), array('e.id', 'e.title', 'e.description', 'e.image', 'e.time_uploaded', 'ci1.value as fullname', 'ci2.value as email', 'u.link as profile', 'e.views', 'e.votes', 'e.shares', 'e.status'))
				->join(array('ci1' => Core_Model_DbTable_CandidateInfo::TABLE_NAME), 'ci1.id_user = e.id_user AND ci1.id_entry_field = '.$id_fullname_field, array())
                ->join(array('ci2' => Core_Model_DbTable_CandidateInfo::TABLE_NAME), 'ci2.id_user = e.id_user AND ci2.id_entry_field = '.$id_email_field, array())
                ->join(array('u' => YouNet_Model_DbTable_Users::TABLE_NAME), 'u.id = e.id_user', array())
				->where('e.id_contest = ?', $id_contest)
				->order('e.id desc');
		return $this->fetchAll($query);
	}

	public function getAllEntriesByIdContest($id_contest)
	{
		return $this->_allByIdContest($id_contest);
	}

	public function countEntryByUser($id_user, $id_contest)
	{
		$query = $this->_countEntryByUserWithoutStatus($id_user, $id_contest);
		$query = $query->where('(status=' . Core_Model_IEntry::STATUS_APPROVED . ' OR status=' . Core_Model_IEntry::STATUS_PENDING . ')');
		$result = $this->fetchAll($query)->current();
		
		return $result->entry_numbers;
	}

	public function countEntryByUserWithoutStatus($id_user, $id_contest)
	{
		$query = $this->_countEntryByUserWithoutStatus($id_user, $id_contest);
		$result = $this->fetchAll($query)->current();
		return $result->entry_numbers;
	}
	
	private function _countEntryByUserWithoutStatus($id_user, $id_contest)
	{
		$query = $this->select()
				->from($this, array('count(id) as entry_numbers'))
				->where('id_contest = ?', $id_contest)
				->where('id_user = ?', $id_user);
		return $query;
	}
	
	public function insertFromParams($params)
	{
		$entry = $this->createRow();
		$entry->setFromArray($params['params']);

		if(isset($params['is_image_uploaded']) && $params['is_image_uploaded'])
		{
			$entry->image = $params['image_name'];
		}

		$entry->id_user = $params['id_user'];
		$entry->id_contest = $params['id_contest'];
		$entry->description = $params['description'];
		$entry->time_uploaded = time();

		if ($params['is_need_for_approve'])
		{
			$entry->status = Core_Model_IEntry::STATUS_PENDING;
		}
		else
		{
			$entry->status = Core_Model_IEntry::STATUS_APPROVED;
		}

		return $entry->save();
	}
    
	public function increaseShareNumber($id_entry)
	{
		return $this->update(
			array('shares' => new Zend_Db_Expr('shares+1')), 
			array('id = ?' => $id_entry)
		);
	}
    
    public function approveListEntries($id_entries, $id_contest)
    {
        return $this->_actionOnListEntries($id_entries, $id_contest, self::STATUS_APPROVED);
    }
	
    public function rejectListEntries($id_entries, $id_contest)
    {
        return $this->_actionOnListEntries($id_entries, $id_contest, self::STATUS_REJECT);
    }
    
    public function deleteListEntries($id_entries, $id_contest)
    {
        $result = $this->_actionOnListEntries($id_entries, $id_contest, self::STATUS_DELETE);
        if(!empty($result)){
            Core_Model_DbTable_Contests::getInstance()->updateSubmissionInfo($id_contest, array(
                'submissions' => new Zend_Db_Expr('submissions - ' . $result)
            ));
        }
    }
    
    private function _actionOnListEntries($id_entries, $id_contest, $status){
        $arrIdEntry = explode(',', $id_entries);
        $id_entries = "'" . preg_replace('/,/', "','", $id_entries) . "'";
        $result = $this->update(array(
            'status' => $status
        ), array(
            'id_contest=?'  => $id_contest,
            "id IN ($id_entries)"
        ));
        $this->_removeCacheOnListEntries($arrIdEntry, $id_contest);
        return $result;
    }
    
    private function _removeCacheOnListEntries($arrIdEntries, $id_contest){
        foreach ($arrIdEntries as $id_entry){
            YouNet_Util::getMemCache()->remove(Core_Cache_IKeys::MEMCACHE_MODEL_ENTRY.$id_entry);
        }
        Core_Model_DbTable_Contests::removeIndexIdEntriesCache($id_contest);
    }

    /**
	 *
	 * @param type $id_contest
	 * @param array $arrFilter
	 * @return Zend_Db_Select
	 */
	public function getSelectionByIdContest($id_contest, array $arrFilter)
	{
		$select = $this->select()
				->setIntegrityCheck(false)
				->from(array('e' => self::TABLE_NAME), array(
					'*' => 'e.*',
					'fullname' => 'i.value',
				))
				->where('e.id_contest = ?', $id_contest)
				->where('e.status != ?', self::STATUS_DELETE);

		$select->joinLeft(
				array('f' => Core_Model_DbTable_EntryFields::TABLE_NAME),
				'e.id_contest = f.id_contest and f.type = ' . Core_Model_IEntryFields::INDEX_FULL_NAME,
				array()
		)->joinLeft(
				array('i' => Core_Model_DbTable_CandidateInfo::TABLE_NAME),
				'i.id_entry_field = f.id AND e.id_user = i.id_user',
				array(
				)
		);



		$select->group('e.id');

		if (!empty($arrFilter[Core_Model_IEntry::PARAM_KEYWORD]))
		{
			$keyword = $arrFilter[Core_Model_IEntry::PARAM_KEYWORD];

			if (empty($arrFilter[Core_Model_IEntry::PARAM_KEYWORD_FILTER]))
			{
				$select->where(" MATCH(i.value, title, description) AGAINST(? IN BOOLEAN MODE)", $keyword);
			}
			else
			{
				if ($arrFilter[Core_Model_IEntry::PARAM_KEYWORD_FILTER] == Core_Model_IEntry::FILTER_BY_TITLE_DESC_VALUE)
				{
					$select->where("MATCH(title, description) AGAINST(? IN BOOLEAN MODE)", $keyword);
					$select->order("MATCH(title, description) AGAINST(" . $this->quote($keyword) . " IN BOOLEAN MODE) DESC");
				}
				if ($arrFilter[Core_Model_IEntry::PARAM_KEYWORD_FILTER] == Core_Model_IEntry::FILTER_BY_REGISTRANT_VALUE)
				{
					$select->where("MATCH(i.value) AGAINST(? IN BOOLEAN MODE)", $keyword);
					$select->order("MATCH(i.value) AGAINST(" . $this->quote($keyword) . " IN BOOLEAN MODE) DESC");
				}
			}
		}
		if (!empty($arrFilter[Core_Model_IEntry::PARAM_STATUS]))
		{
			$select->having('status = ?', $arrFilter[Core_Model_IEntry::PARAM_STATUS]);
		}

		if (!empty($arrFilter))
		{
			$isSort = false;
			foreach ($arrFilter as $key => $value)
			{
				if (in_array($key, array('views', 'votes', 'shares', 'time_uploaded', 'status')))
				{
					if (in_array($value, array('DESC', 'ASC')))
					{
						$isSort = true;
						$select->order("$key $value");
					}
				}
			}
		}

		if (!$isSort)
		{
			$select->order("time_uploaded DESC");
		}
        $select->where('e.status != ?', self::STATUS_DELETE);
		return $select;
	}

	/**
	 *
	 * @param type $id_contest
	 * @param array $keyword
	 * @return Zend_Db_Select
	 */
	private function _getEntriesByIdContest($id_contest, $keyword, $criteria, $sort = null)
	{
		$select = $this->select()
				->setIntegrityCheck(false)
				->from(array('e' => self::TABLE_NAME), array(
					'*' => 'e.*',
					'i1.value as fullname'
				))
				->where('e.id_contest = ?', $id_contest)
				->where('e.status = ?', self::STATUS_APPROVED);

		//Join First Name
		$select->joinLeft(
				array('f1' => Core_Model_DbTable_EntryFields::TABLE_NAME),
				'e.id_contest = f1.id_contest and f1.type = ' . Core_Model_IEntryFields::INDEX_FULL_NAME,
				array()
		)->joinLeft(
				array('i1' => Core_Model_DbTable_CandidateInfo::TABLE_NAME),
				'i1.id_entry_field = f1.id AND i1.id_user = e.id_user',
				array(
				)
		);

		$select->joinLeft(
				array('u' => Core_Model_DbTable_Users::TABLE_NAME),
				'u.id = e.id_user',
				array('u.link')
		);

		if (!empty($keyword))
		{
			$keyword = $this->quote($keyword);

			if ($criteria == Core_Model_IEntry::FILTER_BY_REGISTRANT_VALUE)
			{
				$select->where("MATCH(i1.value) AGAINST($keyword IN BOOLEAN MODE)");
				$select->order("MATCH(i1.value) AGAINST($keyword IN BOOLEAN MODE) DESC");
			}
			else if ($criteria == Core_Model_IEntry::FILTER_BY_TITLE_DESC_VALUE)
			{
				$select->where("MATCH(title, description) AGAINST($keyword IN BOOLEAN MODE)");
				$select->order("MATCH(title, description) AGAINST($keyword IN BOOLEAN MODE) DESC");
			}
		}
        
        if(!is_null($sort)){
            if($sort == self::ENTRIES_LATEST){
                $select->order('time_uploaded DESC');
            } else if ($sort == self::ENTRIES_MOST_POPULAR) {
                $select->order('votes DESC');
            }
        }
        
		$select->group('e.id');

		return $select;
	}

	public function searchEntries($id_contest, $keyword, $criteria, $sort, &$arrListItemsCount, $is_random = true)
	{
        if($sort == self::ENTRIES_RANDOM){
            $session    = Zend_Registry::get('session');
            $random_pages = isset($session->random_pages)?$session->random_pages:array();
            $arrIndexIdEntry = $this->_getIndexIdEntriesByIdContest($id_contest, $keyword, $criteria, $sort);
            
            $paginator = array();
            if(count($arrIndexIdEntry) > 0){
                $arrListItemsCount['total_pages']   = ceil(count($arrIndexIdEntry) / ITEM_COUNT_PER_PAGE);
                if($arrListItemsCount['current_page'] >= $arrListItemsCount['total_pages']){
                    $arrListItemsCount['current_page'] = $arrListItemsCount['total_pages'];
                }
                
                if($arrListItemsCount['current_page'] <= 1){
                    $arrListItemsCount['current_page'] = 1;
                }
                
                array_splice($random_pages, $arrListItemsCount['current_page']);
                $arrIndexIdEntryTemp = $arrIndexIdEntry;
                for($i = 0; $i < $arrListItemsCount['current_page']; $i++){
                    if(!isset($random_pages[$i]) || ($i == ($arrListItemsCount['current_page'] - 1) && $is_random)){
                        $num_rand = (count($arrIndexIdEntryTemp) >= ITEM_COUNT_PER_PAGE)?ITEM_COUNT_PER_PAGE:count($arrIndexIdEntryTemp);
                        $random_pages[$i] = Core_Util::array_random_assoc($arrIndexIdEntryTemp, $num_rand);
                    }
                    $arrIndexIdEntryTemp = array_diff_key($arrIndexIdEntryTemp, $random_pages[$i]);
                }
                
                $session->random_pages = $random_pages;
                $arrRandomIdEntry = $random_pages[$arrListItemsCount['current_page'] - 1];
                if(is_array($arrRandomIdEntry)){
                    foreach ($arrRandomIdEntry as $id_entry){
                        $paginator[] = $this->getEntryDetailForFanPage($id_entry);
                    }
                } else {
                    $paginator[] = $this->getEntryDetailForFanPage($arrRandomIdEntry);
                }
            }
        } else {
            $query = $this->_getEntriesByIdContest($id_contest, $keyword, $criteria, $sort);
            $paginator = Contest_Paginator::factory($query);
            $paginator->setItemCountPerPage(ITEM_COUNT_PER_PAGE);
            $paginator->setCurrentPageNumber($arrListItemsCount['current_page']);
            $arrListItemsCount['total_pages'] = $paginator->count();
        }
        /*
         * Calculate next_page and prev_page
         */
        if($arrListItemsCount['current_page'] >= $arrListItemsCount['total_pages']){
            $arrListItemsCount['next_page'] = $arrListItemsCount['total_pages'];
        } else {
            $arrListItemsCount['next_page'] = $arrListItemsCount['current_page'] + 1;
        }

        if($arrListItemsCount['current_page'] <= 1){
            $arrListItemsCount['prev_page'] = 1;
        } else {
            $arrListItemsCount['prev_page'] = $arrListItemsCount['current_page'] - 1;
        }
        
		return $paginator;
	}
    
    private function _getIndexIdEntriesByIdContest($id_contest, $keyword, $criteria, $sort = null)
	{
        $arrIndexIdEntry = false;
        if(empty($keyword)){
            $arrIndexIdEntry = YouNet_Util::getMemCache()->load(
                Core_Cache_IKeys::MEMCACHE_INDEX_ID_ENTRY_APPROVE.$id_contest
            );
        }
        
        if($arrIndexIdEntry === false){
            $select = $this->select()
                ->setIntegrityCheck(false)
                ->from(array('e' => self::TABLE_NAME), array(
                    'e.id'
                ))
                ->joinLeft(
                        array('f1' => Core_Model_DbTable_EntryFields::TABLE_NAME),
                        'e.id_contest = f1.id_contest and f1.type = ' . Core_Model_IEntryFields::INDEX_FULL_NAME,
                        array()
                )->joinLeft(
                        array('i1' => Core_Model_DbTable_CandidateInfo::TABLE_NAME),
                        'i1.id_entry_field = f1.id AND i1.id_user = e.id_user',
                        array()
                )
                ->where('e.id_contest = ?', $id_contest)
                ->where('e.status = ?', self::STATUS_APPROVED);

            if (!empty($keyword))
            {
                $keyword = $this->quote($keyword);

                if ($criteria == Core_Model_IEntry::FILTER_BY_REGISTRANT_VALUE)
                {
                    $select->where("MATCH(i1.value) AGAINST($keyword IN BOOLEAN MODE)");
                    $select->order("MATCH(i1.value) AGAINST($keyword IN BOOLEAN MODE) DESC");
                }
                else if ($criteria == Core_Model_IEntry::FILTER_BY_TITLE_DESC_VALUE)
                {
                    $select->where("MATCH(title, description) AGAINST($keyword IN BOOLEAN MODE)");
                    $select->order("MATCH(title, description) AGAINST($keyword IN BOOLEAN MODE) DESC");
                }
            }

            if(!is_null($sort)){
                if($sort == self::ENTRIES_LATEST){
                    $select->order('time_uploaded DESC');
                } else if ($sort == self::ENTRIES_MOST_POPULAR) {
                    $select->order('votes DESC');
                }
            }

            $select->group('e.id');
            $arrIndexIdEntry = $this->_db->fetchCol($select);
            if(empty($keyword)){
                YouNet_Util::getMemCache()->save(
                    $arrIndexIdEntry,
                    Core_Cache_IKeys::MEMCACHE_INDEX_ID_ENTRY_APPROVE.$id_contest
                );
            }
        }

		return $arrIndexIdEntry;
	}
	/**
	 *
	 * @param type $id_contest
	 * @param array $arrSort
	 * @return Zend_Db_Select
	 */
	public function getApprovedSelectionByIdContest($id_contest, array $arrSort)
	{
		$maxUserScore = $this->getMaxUserCoreByContestId($id_contest);
		if ($maxUserScore <= 0)
		{
			$maxUserScore = 1;
		}
		$select = $this->select()
				->setIntegrityCheck(false)
				->from(
					array('e' => self::TABLE_NAME),
					array(
						'e.*',
						'user_score' => new Zend_Db_Expr('e.votes + e.shares*2'),
						'total1' => new Zend_Db_Expr("(e.votes + e.shares*2)*5/{$maxUserScore} + IFNULL(score1,0)/2"),
						'total2' => new Zend_Db_Expr("(e.votes + e.shares*2)*5/{$maxUserScore} + IFNULL(score2,0)/2")
					)
				)
				->where('e.id_contest = ?', $id_contest)
				->where('e.status = ?', self::STATUS_APPROVED);
		if (!empty($arrSort))
		{
			foreach ($arrSort as $key => $value)
			{
				if (in_array($key,
						array(
							'views',
							'votes',
							'shares',
							'time_uploaded',
							'status',
							'user_score',
							'total1',
							'total2',
							'score1',
							'score2'
						)
				))
				{
					if (in_array($value, array('DESC', 'ASC')))
					{
						switch ($key)
						{
							case 'score1':
							case 'score2':
								$select->order("IFNULL($key,-1) $value");
								break;
							default:
								$select->order("$key $value");
								break;
						}
					}
				}
			}
		}
		else
		{
			$select->order("time_uploaded DESC");
		}
		return $select;
	}

	public function getMaxUserCoreByContestId($id_contest)
	{
		$result = $this->select()->from(
								array('e' => $this->_name),
								array('max_user_score' => new Zend_Db_Expr('MAX(e.votes + e.shares*2)'))
						)
						->where('id_contest = ?', $id_contest)->limit(1)->query()->fetchColumn(0);
		return $result;
	}

	/**
	 *
	 * @param type $id_user
	 * @param type $entry_status \
	 */
	private function countSubmissionByStatus($id_user, $entry_status = Core_Model_IEntry::STATUS_APPROVED)
	{
		$query = $this->select()
				->from($this, array('count(*) as number_of_submission'))
				->where('status = ?', $entry_status);

		$result = $this->fetchAll($query)->current();
		return $result->number_of_sumission;
	}

	public function countUnapprovedSubmission($id_user)
	{
		return $this->countSubmissionByStatus($id_user, Core_Model_IEntry::STATUS_PENDING);
	}

	public function countApprovedSubmissionByAPairUserAndContest($id_user, $id_contest)
	{
		$query = $this->select()
				->from($this, array('count(id) as entry_numbers'))
				->where('id_contest = ?', $id_contest)
				->where('id_user = ?', $id_user)
				->where('status = ?', self::STATUS_APPROVED);

		$result = $this->fetchAll($query)->current();

		return $result->entry_numbers;
	}
    
    public function countApprovedSubmissionByContest($id_contest)
    {
        $query = $this->select()
				->from($this, array('count(id) as entry_numbers'))
				->where('id_contest = ?', $id_contest)
				->where('status = ?', self::STATUS_APPROVED);
        return $this->getAdapter()->fetchOne($query);
    }

	public static function getArrOptionStatus()
	{
		return array(
			self::STATUS_PENDING => 'STATUS_LABEL_PENDING',
			self::STATUS_APPROVED => 'STATUS_LABEL_APPROVED',
			self::STATUS_REJECT => 'STATUS_LABEL_REJECTED',
		);
	}

	/**
	 * Don't use
	 * @deprecated
	 * @param type $id_entry
	 * @param type $id_page
	 * @return type 
	 */
	public function getShareEntry($id_entry, $id_page)
	{
		$query = $this->select()->from(array('e' => self::TABLE_NAME), array('e.*'))
				->join(array('cp' => Core_Model_DbTable_Pages::TABLE_NAME), 'e.id_contest = cp.id_coantest', array())
				->where('e.id=?', $id_entry)
				->where('cp.id_page=?', $id_page);
		return $this->fetchAll($query)->current();
	}

	public function createRow(array $data = array(), $defaultSource = null)
	{
		$fullname = '';
		if (isset($data['fullname']))
		{
			$fullname = $data['fullname'];
			unset($data['fullname']);
		}
		$link = '';
		if (isset($data['link']))
		{
			$link = $data['link'];
			unset($data['link']);
		}
		$model = parent::createRow($data, $defaultSource);
		$model->fullname = $fullname;
		$model->link = $link;
		return $model;
	}

	public static function getStatusLabelByInt($status)
	{
		$statusLabel = '';
		if ($status == self::STATUS_PENDING)
		{
			$statusLabel = 'STATUS_LABEL_PENDING';
		}
		else if ($status == self::STATUS_APPROVED)
		{
			$statusLabel = 'STATUS_LABEL_APPROVED';
		}
		else if ($status == self::STATUS_REJECT)
		{
			$statusLabel = 'STATUS_LABEL_REJECTED';
		}
		else if ($status == self::STATUS_DELETE)
		{
			$statusLabel = 'STATUS_LABEL_APPROVED';
		}
		else
		{
			throw new Exception('unexpected status');
		}
		return $statusLabel;
	}

    public function getCurrentPage($id_entry,$id_contest)
    {
        $sql = $this->select()->from($this->_name, array('count' => 'COUNT(DISTINCT id)'))
                ->where('id > ' . $id_entry)
                ->where('id_contest = ' . $id_contest)
                ->where('status = ' . self::STATUS_APPROVED);
        $result = $this->_db->fetchRow($sql);
        return intval($result['count'] / ITEM_COUNT_PER_PAGE) + 1;
    }
	
	public function addView($params)
	{
		$query = "INSERT DELAYED INTO ". Core_Model_DbTable_EntryViews::TABLE_NAME . " ("; 
		$col = array();
		$val = array();
		foreach ($params as $id => $key)
		{
			$col[] = $id;
			$val[] = $key;
		}
		$query .= implode(',', $col) . ") VALUES (";
		$query .= implode(',', $val) . ")";
		$this->getAdapter()->query($query);
	}
	public function increaseView($id_entry)
	{
		$query = "UPDATE LOW_PRIORITY ". Core_Model_DbTable_Entries::TABLE_NAME . " SET views = views + 1 WHERE id = " . $this->quote($id_entry);
		$this->getAdapter()->query($query);
	}
    
    public static function getArrayViewTypes()
    {
        return array(
            self::ENTRIES_LATEST        => YouNet_Util::translate('Latest entries'),
            self::ENTRIES_MOST_POPULAR  => YouNet_Util::translate('Most popular'),
            self::ENTRIES_RANDOM        => YouNet_Util::translate('Random')
        );
    }
    
    private function _getSqlEntryDetailForFanpage($id_entry){
        $select = $this->select()
				->setIntegrityCheck(false)
				->from(array('e' => self::TABLE_NAME), array(
					'*' => 'e.*',
					'i1.value as fullname'
				))
                ->joinLeft(
                        array('f1' => Core_Model_DbTable_EntryFields::TABLE_NAME),
                        'e.id_contest = f1.id_contest and f1.type = ' . Core_Model_IEntryFields::INDEX_FULL_NAME,
                        array()
                )->joinLeft(
                        array('i1' => Core_Model_DbTable_CandidateInfo::TABLE_NAME),
                        'i1.id_entry_field = f1.id AND i1.id_user = e.id_user',
                        array(
                        )
                )
                ->joinLeft(
                        array('u' => Core_Model_DbTable_Users::TABLE_NAME),
                        'u.id = e.id_user',
                        array('u.link')
                )
                ->where('e.id = ?', $id_entry)
				->where('e.status = ?', self::STATUS_APPROVED);
        return $select;
    }
    
    public function getEntryDetailForFanPage($id_entry)
    {
        $entryData = YouNet_Util::getMemCache()->load(
            Core_Cache_IKeys::MEMCACHE_MODEL_ENTRY.$id_entry
        );

        if( $entryData === false)
        {
            $select     = $this->_getSqlEntryDetailForFanpage($id_entry);
            $entry		= $this->fetchRow($select);
            if (!empty($entry))
            {
                $entryData	= $entry->toArray();
                YouNet_Util::getMemCache()->save(
                    $entryData,
                    Core_Cache_IKeys::MEMCACHE_MODEL_ENTRY.$id_entry
                );
            }
        }
        else
        {
            $entry = $this->createRow($entryData);
        }
        return $entry;
    }
}

